package cn.test.utils;

import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelId;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.apache.commons.lang3.StringUtils;


import java.util.concurrent.ConcurrentHashMap;

public class DeviceData {
    /***
     * 存储每一个客户端接入进来时的Channel对象
     */
    private static ChannelGroup group = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    /**
     * 设备号，channel id
     */
    private static ConcurrentHashMap<ChannelId,String> channelMap = new ConcurrentHashMap();


    public static void remove(Channel channel) {
        channelMap.remove(channel.id());
        group.remove(channel);

    }
    public static void add(Channel channel) {
        channelMap.put(channel.id(),"");
        group.add(channel);

    }

    public static String getDeviceName(Channel channel) {
        String deviceKey=channelMap.get(channel.id());

        if (StringUtils.isEmpty(deviceKey)) {
            deviceKey = "未知设备";
        }
        return deviceKey;

    }

    public static boolean setDeviceKey(Channel channel, String deviceKey) {
        String device=channelMap.get(channel.id());
        if (device == null) {
            System.out.println("设备注册异常，未知设备");
        }
        channelMap.put(channel.id(), deviceKey);
        return true;
    }

    public static void send(int[] data) {
        ByteBuf d = ByteBufUtil.hexToByteBuf(data);
        group.writeAndFlush(d);
    }

    public static void close() {
        group.close().awaitUninterruptibly();
    }
}
